package com.redsun.smallworld.tools;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.text.SimpleDateFormat;

/**
 * Created by zhebinwang on 2017/6/2.
 */
public class JsonUtil {


    public static <T> T extractData(String response, Class<T> tClass) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
        JsonNode rootNode = objectMapper.readTree(response);
        if (!rootNode.has("data")) {
            return null;
        }
        JsonNode dataNode = rootNode.findValue("data");
        String data = objectMapper.writeValueAsString(dataNode);
        T t = objectMapper.readValue(data, tClass);
        return t;
    }

    public static String parseObjToJsonString(Object obj) {
        if (obj == null) {
            return "";
        }
        ObjectMapper mapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"));
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }
}
